package com.miracle.system.service.impl;

import com.miracle.common.utils.DictUtils;
import com.miracle.system.domain.SysDictH;
import com.miracle.system.domain.SysDictL;
import com.miracle.system.mapper.SysDictHMapper;
import com.miracle.system.mapper.SysDictLMapper;
import com.miracle.system.service.SysDictHService;
import com.miracle.system.service.SysDictLService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据字典 业务层处理
 *
 * @author miracle
 */
@Service
public class SysDictHServiceImpl implements SysDictHService
{
    @Resource
    SysDictHMapper dictHMapper;
    @Resource
    SysDictLMapper dictLMapper;

    @Autowired
    SysDictLService dictLService;

    @PostConstruct
    public void init(){
        SysDictH dictHQuery = new SysDictH();
        dictHQuery.setStatus("enabled");
        List<SysDictH> dictHList = dictHMapper.selectDictHList(dictHQuery);
        for (SysDictH dictH: dictHList) {
            List<SysDictL> dictLList = dictLMapper.selectDictLByDictTypeCode(dictH.getDictTypeCode());
            DictUtils.setDictCache(dictH.getDictTypeCode(),dictLList);
        }
    }
    @Override
    public List<SysDictH> selectDictHList(SysDictH dictH) {
        return dictHMapper.selectDictHList(dictH);
    }

    @Override
    public void refreshCache() {
        DictUtils.clearDictCache();
        init();
    }

    @Override
    @Transactional
    public Integer insertDictH(SysDictH dictH) {
        Integer rows = dictHMapper.insertDictH(dictH);
        Integer dictTypeId = dictH.getDictTypeId();
        List<SysDictL> dictLList = new ArrayList<SysDictL>();
        for (SysDictL dictL: dictH.getDictLList()) {
            dictL.setDictTypeId(dictTypeId);
            dictL.setCreateBy(dictH.getCreateBy());
            dictLList.add(dictL);
        }
        dictLMapper.batchInsertDictL(dictLList);
        return rows;
    }

    @Override
    @Transactional
    public Integer deleteDictHByDictTypeIds(Integer[] dictTypeIds) {
        dictLMapper.deleteDictLByDictTypeIds(dictTypeIds);
        return dictHMapper.deleteDictHByDictTypeIds(dictTypeIds);
    }

    @Override
    public Integer updateDictH(SysDictH dictH) {
        dictLService.updateDictL(dictH);
        return dictHMapper.updateDictH(dictH);
    }

    @Override
    public SysDictH selectDictHByDictTypeId(Integer dictTypeId) {
        SysDictH dictH = dictHMapper.selectDictHByDictTypeId(dictTypeId);
        List<SysDictL> dictLList = dictLMapper.selectDictLByDictTypeId(dictTypeId);
        dictH.setDictLList(dictLList);
        return dictH;
    }

    @Override
    public SysDictH remoteCheckDictH(SysDictH dictH) {
        return dictHMapper.remoteCheckDictH(dictH);
    }
}
